package com.slofzx.nuoda.evaluation.version.controller;

import com.slofzx.nuoda.common.annotation.SysLog;
import com.slofzx.nuoda.common.enums.CommonResultEnum;
import com.slofzx.nuoda.common.util.DataConvertUtil;
import com.slofzx.nuoda.common.vo.FileVO;
import com.slofzx.nuoda.evaluation.compute.data.service.ComputeDetailDataService;
import com.slofzx.nuoda.evaluation.core.util.StringUtil;
import com.slofzx.nuoda.evaluation.version.dto.ComputeVersionDTO;
import com.slofzx.nuoda.evaluation.version.service.ComputeVersionService;
import com.slofzx.nuoda.evaluation.dto.MonteCarloItemDTO;
import com.slofzx.nuoda.evaluation.version.vo.ComputeVersionVO;
import com.slofzx.nuoda.evaluation.version.vo.ProjectComputeVersionLockVO;
import com.slofzx.nuoda.evaluation.vo.MonteCarloAnalysisResultVO;
import com.slofzx.nuoda.excel.vo.ExcelPreviewDataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.slofzx.nuoda.common.controller.BaseController;
import com.slofzx.nuoda.common.vo.AjaxResultVO;
import com.slofzx.nuoda.common.vo.PageResultVO;
import com.slofzx.nuoda.common.enums.ServiceResult;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 评价信息控制层
 *
 * @author nuoda
 * @menu 评价信息
 * @since 2021-11-19 15:56:07
 */
@RestController
@RequestMapping("/compute_version")
public class ComputeVersionController extends BaseController {
    /**
     * 服务对象
     */
    @Autowired
    private ComputeVersionService computeVersionService;

    @Autowired
    private ComputeDetailDataService computeDetailDataService;

    /**
     * 通过查询条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @GetMapping("/data")
    public AjaxResultVO<List<ComputeVersionVO>> queryList(ComputeVersionDTO dto) {
//            //TODO 数据迁移
//        List<ComputeVersion> versionList = this.computeVersionDAO.selectList(null);
//        logger.info("共需转移 {} 条数据",versionList.size());
//        int i=0;
//        for(ComputeVersion item:versionList) {
//            if(item.getIrrAfterTax()==0&&item.getIrrBeforeTax()==0) {
//                continue;
//            }
////            ComputeData data = computeDataDAO.getComputeData(item.getId());
//            ComputeDetailDataVO data = computeDetailDataClient.queryById(item.getId()).getData();
//            if(data == null) {
//                logger.info("迁移数据未找到对应版本数据:{}",item.getId());
//                continue;
//            }
//            logger.info("开始转移第 {} 条数据",++i);
////            computeDetailDataService.deleteBySource("project",item.getProjectId());
//            ComputeDetailDataDTO dataDTO = new ComputeDetailDataDTO();
//            dataDTO.setId(item.getId());
//            dataDTO.setSourceId(data.getSourceId());
//            dataDTO.setModelId(data.getModelId());
//            dataDTO.setSourceType(data.getSourceType());
//            dataDTO.setMark(data.getMark());
//            dataDTO.setDetail(data.getDetail());
//            computeDetailDataService.create(dataDTO);
//        }

        List<ComputeVersionVO> dataList = computeVersionService.queryList(dto);
        return PageResultVO.newSuccessResult(dataList, dto.getCount());
    }

    @GetMapping("/versionData")
    public AjaxResultVO<List<ProjectComputeVersionLockVO>> queryVersionLock(ComputeVersionDTO dto) {
        List<ProjectComputeVersionLockVO> dataList = computeVersionService.queryVersionData(dto);
        return PageResultVO.newSuccessResult(dataList,dto.getCount());
    }
    /**
     * 锁定版本
     *
     * @param dto 参数数据
     * @return 操作结果
     */
    @ResponseBody
    @PostMapping(value = "/lock")
    public AjaxResultVO copy(@RequestBody List<ComputeVersionDTO> dtos) {
        ServiceResult resultEnum = computeVersionService.lock(dtos);
        return AjaxResultVO.getInstance(resultEnum);
    }

    /**
     * 通过查询条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @PostMapping("/query")
    public AjaxResultVO<List<ComputeVersionVO>> search(@RequestBody ComputeVersionDTO dto) {
        List<ComputeVersionVO> dataList = computeVersionService.queryList(dto);
        return PageResultVO.newSuccessResult(dataList, dto.getCount());
    }

    /**
     * 创建数据
     *
     * @param dto 参数数据
     * @return 操作结果
     */
    @ResponseBody
    @PostMapping(value = "/create")
    public AjaxResultVO create(@RequestBody ComputeVersionDTO dto) {
        ServiceResult resultEnum = computeVersionService.create(dto);
        if(resultEnum == CommonResultEnum.SUCCESS) {
            return AjaxResultVO.newSuccessResult(dto.getId());
        }
        return AjaxResultVO.getInstance(resultEnum);
    }
    /**
     * 创建版本并自动计算
     *
     * @param dto 参数数据
     * @return 操作结果
     */
    @SysLog(title = "评价计算")
    @ResponseBody
    @PostMapping(value = "/create_auto_compute")
    public AjaxResultVO createAutoCompute(@RequestBody ComputeVersionDTO dto) {
        dto.setAutoCompute(true);
        ServiceResult resultEnum = computeVersionService.create(dto);
        if(resultEnum == CommonResultEnum.SUCCESS) {
            return AjaxResultVO.newSuccessResult(dto.getId());
        }
        return AjaxResultVO.getInstance(resultEnum);
    }
    /**
     * 另存为版本
     *
     * @param dto 参数数据
     * @return 操作结果
     */
    @ResponseBody
    @PostMapping(value = "/copy")
    public AjaxResultVO copy(@RequestBody ComputeVersionDTO dto) {
        ServiceResult resultEnum = computeVersionService.copy(dto);
        if(resultEnum == CommonResultEnum.SUCCESS) {
            return AjaxResultVO.newSuccessResult(dto.getId());
        }
        return AjaxResultVO.getInstance(resultEnum);
    }

    /**
     * 数据更新
     *
     * @param dto
     * @return 操作结果
     */
    @ResponseBody
    @PostMapping(value = "/update")
    public AjaxResultVO update(@RequestBody ComputeVersionDTO dto) {
        ServiceResult resultEnum = computeVersionService.update(dto);
        return AjaxResultVO.getInstance(resultEnum);
    }
//    /**
//     * 保存未保存版本
//     *
//     * @param dto
//     * @return 操作结果
//     */
//    @ResponseBody
//    @PostMapping(value = "/save_temp")
//    public AjaxResultVO saveTemp(@RequestBody ComputeVersionDTO dto) {
//        ServiceResult resultEnum = computeVersionService.saveTemp(dto);
//        return AjaxResultVO.getInstance(resultEnum);
//    }

    /**
     * 删除数据
     *
     * @param id
     * @return 操作结果
     */
    @ResponseBody
    @PostMapping(value = "/delete")
    public AjaxResultVO delete(String id) {
        ServiceResult resultEnum = computeVersionService.deleteById(id);
        return AjaxResultVO.getInstance(resultEnum);
    }

    /**
     * 查询单个数据
     *
     * @return id对应数据
     */
    @ResponseBody
    @GetMapping(value = "/info/{id}")
    public AjaxResultVO<ComputeVersionVO> queryById(@PathVariable String id) {
        ComputeVersionVO vo = computeVersionService.queryById(id);
        return AjaxResultVO.newSuccessResult(vo);
    }

    /**
     * 查询单个数据
     *
     * @return id对应数据
     */
    @ResponseBody
    @PostMapping(value = "/invoke")
    public AjaxResultVO<ComputeVersionVO> queryById(@RequestBody ComputeVersionDTO dto) {
        ServiceResult resultEnum = computeVersionService.computeResult(dto);
        if(resultEnum!= CommonResultEnum.SUCCESS) {
            return AjaxResultVO.getInstance(resultEnum);
        }
        return AjaxResultVO.newSuccessResult(dto.getId());
    }

    @ResponseBody
    @GetMapping("/input/{dataVersion}")
    public AjaxResultVO inputData(@PathVariable String dataVersion) {
        return AjaxResultVO.newSuccessResult(computeDetailDataService.getComputeInputDataMap(dataVersion));
    }
    @ResponseBody
    @GetMapping("/result/preview")
    public AjaxResultVO<ExcelPreviewDataVO> previewResult(@RequestParam String dataVersion) {
        return AjaxResultVO.newSuccessResult(computeVersionService.previewComputeResult(dataVersion));
    }
    @ResponseBody
    @GetMapping("/result/download")
    public ResponseEntity<byte[]> downloadResult(@RequestParam String dataVersion) {
        FileVO fileVO = computeVersionService.downloadComputeResult(dataVersion);
        HttpHeaders headers = new HttpHeaders();
        headers.add("content-disposition", "attachment; filename=" + fileVO.getName());
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(fileVO.getData(), headers, statusCode);
        return entity;
    }

    /**
     * 蒙特卡洛计算
     * @param dataVersion
     * @param config
     * @return
     */
    @ResponseBody
    @PostMapping("/monte_carlo/result")
    AjaxResultVO<MonteCarloAnalysisResultVO> monteKarloResult(@RequestParam String dataVersion, @RequestBody Map<String, MonteCarloItemDTO> config){
        MonteCarloAnalysisResultVO resultVO = computeVersionService.computeMontecaloResult(dataVersion,config);
        return AjaxResultVO.newSuccessResult(resultVO);
    }

    @SysLog(title = "拉齐计算")
    @ResponseBody
    @PostMapping("/cash_flow_pull")
    public AjaxResultVO cashFlowPull(@RequestBody ComputeVersionDTO dto) {
        ServiceResult resultEnum = computeVersionService.cashFlowPull(dto);
        if(resultEnum!= CommonResultEnum.SUCCESS) {
            return AjaxResultVO.getInstance(resultEnum);
        }
        return AjaxResultVO.newSuccessResult(dto.getId());
    }

    /**
     * 执行有无项目对减
     * @param dto 录入数据
     * @return
     */
    @SysLog(title = "有无项目对减")
    @ResponseBody
    @PostMapping("/subtract")
    public AjaxResultVO subtract(@RequestBody ComputeVersionDTO dto) {
        ServiceResult resultEnum = computeVersionService.subtractResult(dto);
        if(resultEnum!= CommonResultEnum.SUCCESS) {
            return AjaxResultVO.getInstance(resultEnum);
        }
        return AjaxResultVO.newSuccessResult(dto.getId());
    }

    @SysLog(title = "多油价计算")
    @GetMapping("/download/multi_oil_price")
    public ResponseEntity<byte[]> generateMultiPriceExcel(HttpServletRequest request, @RequestParam String dataVersion, @RequestParam String prices) {
        List<Double> priceList = new ArrayList<>();
        String[] priceArray = prices.split(",");
        for(String str:priceArray) {
            if(str.length()<1){
                continue;
            }
            priceList.add(DataConvertUtil.parse2Double(str));
        }
        FileVO fileVO = computeVersionService.getMultiPriceComputeResultFile(dataVersion,priceList);
        if(fileVO == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("content-disposition", "attachment; filename=" + StringUtil.convertDownloadFileName(fileVO.getName(),request.getHeader("User-Agent")));
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(fileVO.getData(), headers, statusCode);
        return entity;
    }

    /**
     * 查询最大版本号
     *
     * @param projectId 查询参数
     * @return 列表数据
     */
    @GetMapping("/maxNum/{projectId}")
    public AjaxResultVO<Integer> queryMaxVersionNum(@PathVariable String projectId) {
        Integer maxVersionNum = computeVersionService.queryMaxVersionNum(projectId);
        return PageResultVO.newSuccessResult(maxVersionNum);
    }

    @ResponseBody
    @GetMapping("/log/download")
    public ResponseEntity<byte[]> downloadLog(@RequestParam String dataVersion) {
        FileVO fileVO = computeVersionService.downloadComputeLog(dataVersion);
        HttpHeaders headers = new HttpHeaders();
        headers.add("content-disposition", "attachment; filename=" + fileVO.getName());
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(fileVO.getData(), headers, statusCode);
        return entity;
    }
}
